package com.bdqn.springweb;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SysUserControllerTester {
    @Resource
    private WebApplicationContext wac;//注入Spring Web上下文的环境
    private MockMvc mockMvc;

    @Before     //代表在测试启动时需要提前加载的内容
    public void setup(){
        //提前加载MVC环境
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    /**
     * 测试根据id查询数据（get请求）
     * @throws Exception
     */
    @Test
    public void testGetUser() throws Exception {
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/user/6")).andReturn().getResponse().getContentAsString();//返回响应主体内容
        System.out.println("Result=========>"+mvcResult);
    }

    /**
     * 测试新增（post请求）
     */
    @Test
    public void testAddUser() throws Exception{
        //构造请求函数
        final MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        params.add("usrName","RESTFUL");
        params.add("usrPassword","123456");
        params.add("usrRoleId","2");
        params.add("usrFlag","1");
        mockMvc.perform(MockMvcRequestBuilders.post("/user").params(params)).
                andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
    }

}
